package com.jc.service.jg;

import java.io.File;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.jc.common.util.Base64Util;
import com.jc.common.util.DateTimeUtil;
import com.jc.common.util.ImageUtil;
import com.jc.common.util.UrlUtil;
import com.jc.ds.model.SupplierGoods;
import com.jc.ds.model.SupplierGoodsPictureList;
import com.jc.ds.model.SupplierProduct;
import com.jc.ds.model.SupplierProductPrice;
import com.jc.framework.enums.GoodNatureType;
import com.jc.framework.enums.GoodsDescType;
import com.jc.framework.enums.ImageType;
import com.jc.framework.enums.Push;
import com.jc.framework.exception.ServiceException;
import com.jc.service.attribute.AttributeService;
import com.jc.service.jg.mq.MqUtil;
import com.jc.service.model.jg.GoodsDetail;
import com.jc.service.model.jg.GoodsNavigate;
import com.jc.service.model.jg.GoodsSendVo;
import com.jc.service.model.jg.Inventory;
import com.jc.service.model.jg.ProductSendVo;
import com.jc.service.model.jg.RequestBaseModel;
import com.jc.service.supplier.SupplierService;
import com.jc.service.supplier_product.SupplierProductService;
import com.jc.service.supplier_product.SupplierProductServiceImpl;
import com.jc.service.suppliergoods.SupplierGoodsService;
import com.jc.service.suppliergoodspicturelist.SupplierGoodsPictureListService;
import com.jc.service.suppliergoodspicturelist.SupplierGoodsPictureListServiceImpl;
import com.jc.service.supplierproductprice.SupplierProductPriceService;
import com.jc.upload.aliyun.oos.AliyunOssUtil;

@Service
public class JgServiceImpl implements JgService {

	Logger log = LoggerFactory.getLogger(JgServiceImpl.class);

	@Autowired
	SupplierGoodsService supplierGoodsService;
	@Autowired
	SupplierGoodsPictureListService supplierGoodsPictureListService;
	@Autowired
	SupplierProductService supplierProductService;
	@Autowired
	SupplierService supplierService;
	
	@Autowired
	AttributeService attributeService;
	@Autowired
	SupplierProductPriceService supplierProductPriceService;

	@Override
	public void receiveGoodsData(RequestBaseModel model) {
		try {
			List<GoodsSendVo> goodsSendVoList = JSON.parseObject(Base64Util.decode(model.getData()),
					new TypeReference<List<GoodsSendVo>>() {
					});
			for (GoodsSendVo goods : goodsSendVoList) {
				MqUtil.queue.put(goods);
			}
		} catch (Exception e) {
			throw new ServiceException(e);
		} 
	}

	public void saveGoodsPicture(GoodsSendVo goods) throws Exception {
//		String localPath = "/usr/local/jg/";
//		String datestr = DateTimeUtil.getDate(new Date(), "yyyyMMdd");
//
//		String goodsName = goods.getName();
//		if (StringUtils.isBlank(goodsName)) {
//			goodsName = "" + goods.getId();
//		}
//		String slocalPath = localPath + datestr + "/" + goodsName;
//		String sslocalPath = localPath + datestr + "/压缩后/" + goodsName;

//		String tit = "轮播图";
//		List<GoodsNavigate> goodsNavigateList = goods.getGoodsNavigateList();

//		for (GoodsNavigate na : goodsNavigateList) {
//			String url = na.getNavigateImage();
//			String fileName = UUID.randomUUID().toString().replaceAll("-", "");
//			if (!StringUtils.isBlank(url)) {
//				// 取扩展名
//				String extName = UrlUtil.getFileExtension(url);
//
//				String filePath = slocalPath + "/" + tit + "/" + fileName + "." + extName;
//				File f = new File(slocalPath + "/" + tit + "/");
//				if (!f.exists()) {
//					f.mkdirs();
//				}
//				String fileYaSuoPath = sslocalPath + "/" + tit + "/" + fileName + "." + extName;
//				File f2 = new File(sslocalPath + "/" + tit + "/");
//				if (!f2.exists()) {
//					f2.mkdirs();
//				}
//
//				ImageUtil.downloadPicture(url, filePath);
//				ImageUtil.outputQuality(filePath, 0.5, fileYaSuoPath, new BigDecimal("100"));
//			}
//		}

//		String tit2 = "详情图";
//		List<GoodsDetail> goodsDetailList = goods.getGoodsDetailList();
//
//		for (GoodsDetail gd : goodsDetailList) {
//			String url = gd.getImagePath();
//			String fileName = UUID.randomUUID().toString().replaceAll("-", "");
//			if (!StringUtils.isBlank(url)) {
//				String extName = UrlUtil.getFileExtension(url);
//
//				String filePath = slocalPath + "/" + tit2 + "/" + fileName + "." + extName;
//				File f = new File(slocalPath + "/" + tit2 + "/");
//				if (!f.exists()) {
//					f.mkdirs();
//				}
//				String fileYaSuoPath = sslocalPath + "/" + tit2 + "/" + fileName + "." + extName;
//				File f2 = new File(sslocalPath + "/" + tit2 + "/");
//				if (!f2.exists()) {
//					f2.mkdirs();
//				}
//				ImageUtil.downloadPicture(url, filePath);
//				ImageUtil.outputQuality(filePath, 0.5, fileYaSuoPath, new BigDecimal("100"));
//				log.error("  <<<<<<<<<<< 已经保存一张详情图...... :  " + goodsName);
//			}
//		}

		saveGoodsInfo(goods);
	}

	@Transactional
	public void saveGoodsInfo(GoodsSendVo goods) {
		String supplier_id = "1001";
		// 保存货品信息
		SupplierGoods _supplier_goods = new SupplierGoods();
		_supplier_goods.setSupplierId(Integer.parseInt(supplier_id));
		_supplier_goods.setSupplierName("吉贡云");
		if (goods != null && goods.getId() > 0) {
			_supplier_goods.setSupplierGoodsId(String.valueOf(goods.getId()));
		}

		// 防重复写入
		// existList
		List<SupplierGoods> existList = supplierGoodsService.queryAll(_supplier_goods);

		if (CollectionUtils.isNotEmpty(existList)) {
			_supplier_goods.setId(existList.get(0).getId());
			// 暂时返回后面要写更新产品逻辑
			// 与技术沟通后后，对于吉贡渠道商口，后面更新的话，需要更新三个字段，（产品名称，价格，规格）本次不做更新逻辑
		} else {
			if (goods != null && goods.getBrandId() > 0) {
				_supplier_goods.setBrandid(Long.valueOf(goods.getBrandId()));
			}
			if (goods != null && StringUtils.isNotBlank(goods.getName())) {
				_supplier_goods.setName(goods.getName());
			}
			if (goods != null && StringUtils.isNotBlank(goods.getBrandNameCn())) {
				_supplier_goods.setBrandnamecn(goods.getBrandNameCn());
			}
			if (goods != null && StringUtils.isNotBlank(goods.getBrandNameEn())) {
				_supplier_goods.setBrandnameen(goods.getBrandNameEn());
			}
			if (goods != null && goods.getCategoryId() > 0) {
				_supplier_goods.setCategoryId(goods.getCategoryId());
			}
			if (goods != null && StringUtils.isNotBlank(goods.getCategoryName())) {
				_supplier_goods.setCategoryName(goods.getCategoryName());
			}

			if (goods != null && goods.getCategoryParentId() > 0) {
				_supplier_goods.setCategoryParentId(goods.getCategoryParentId());
			}

			if (goods != null && StringUtils.isNotBlank(goods.getCategoryParentName())) {
				_supplier_goods.setCategoryParentName(goods.getCategoryParentName());
			}
			_supplier_goods.setGoodsDesc(GoodsDescType.PIC.toString());
			_supplier_goods.setGoodNatureType(GoodNatureType.MATERIAL.getName());
			_supplier_goods.setCreateTime(new Date());
			_supplier_goods.setLastUpdateTime(new Date());
			if (StringUtils.isNotBlank(goods.getSpecDesc())) {
				_supplier_goods.setSpecificationsString(goods.getSpecDesc());
				try {
					attributeService.initAttribute(goods.getSpecDesc());
				} catch (Exception e) {
				}
			}
			supplierGoodsService.add(_supplier_goods, false);

			// 保存货品轮播图信息
			List<GoodsNavigate> goodsNavigateList = goods.getGoodsNavigateList();
			for (GoodsNavigate nav : goodsNavigateList) {
				SupplierGoodsPictureList _nav = new SupplierGoodsPictureList();
				_nav.setGid(_supplier_goods.getId());
				if (StringUtils.isNotBlank(nav.getNavigateImage())) {
					_nav.setImagePath(nav.getNavigateImage());

					String selfImageUrl = imageZipUpload(nav.getNavigateImage());
					_nav.setSelfImagePath(selfImageUrl);

				}
				_nav.setImageType(ImageType.ROTATION.getName());
				if (goods != null && goods.getId() > 0) {
					_nav.setGoodsId("" + goods.getId());
				}
				supplierGoodsPictureListService.add(_nav, false);
			}
			// 保存货品详情图信息
			List<GoodsDetail> goodsDetailList = goods.getGoodsDetailList();
			for (GoodsDetail detailPic : goodsDetailList) {

				SupplierGoodsPictureList _nav = new SupplierGoodsPictureList();
				_nav.setGid(_supplier_goods.getId());
				if (StringUtils.isNotBlank(detailPic.getImagePath())) {
					_nav.setImagePath(detailPic.getImagePath());
					String selfImageUrl = imageZipUpload(detailPic.getImagePath());
					_nav.setSelfImagePath(selfImageUrl);
				}
				if (detailPic.getImageHeight() > 0) {
					_nav.setHeight(detailPic.getImageHeight());
				}
				if (detailPic.getImageWidth() > 0) {
					_nav.setWidth(detailPic.getImageWidth());
				}
				if (detailPic.getOrderNo() > -1) {
					_nav.setImageOrder(detailPic.getOrderNo());
				}
				_nav.setImageType(ImageType.DETAILS.getName());
				if (goods != null && goods.getId() > 0) {
					_nav.setGoodsId("" + goods.getId());
				}

				if (supplierGoodsPictureListService == null) {
					supplierGoodsPictureListService = new SupplierGoodsPictureListServiceImpl();
				}
				supplierGoodsPictureListService.add(_nav, false);
			}

		}

		// 保存SKU信息
		List<ProductSendVo> products = goods.getProducts();
		for (ProductSendVo vo : products) {
			SupplierProduct sp = new SupplierProduct();
			if (vo.getId() > 0) {
				sp.setProductId(String.valueOf(vo.getId()));
			}
			if (_supplier_goods.getId() > 0) {
				sp.setGid(_supplier_goods.getId());
			}
			Inventory inventory = vo.getInventory();
			List<SupplierProduct> queryAll = supplierProductService.queryAll(sp);
			if (CollectionUtils.isNotEmpty(queryAll)) {
				SupplierProduct to = queryAll.get(0);
				if (inventory != null) {
					to.setInventoryNum(inventory.getInventoryNum());
					to.setInventoryId("" + inventory.getId());
					to.setStoreId(""+inventory.getStoreId());
					to.setProductInventoryId(""+inventory.getId());
					supplierProductService.modify(to, false);
				}
				continue;
			}
			if (goods != null && StringUtils.isNotBlank(goods.getName())) {
				sp.setProductName(goods.getName());
			}
			
			if (inventory != null && inventory.getId() > 0) {
				
			}
			if (inventory != null) {
				sp.setInventoryNum(inventory.getInventoryNum());
				if(inventory.getId() > 0)sp.setInventoryId("" + inventory.getId());
				if(inventory.getStoreId() > 0)sp.setStoreId(""+inventory.getStoreId());
				if(inventory.getId() > 0)sp.setProductInventoryId(String.valueOf(inventory.getId()));
			}
			
			if (StringUtils.isNotBlank(vo.getImagePath())) {
				sp.setProductImagePath(vo.getImagePath());
				String selfImageUrl = imageZipUpload(vo.getImagePath());
				sp.setSelfProductImagePath(selfImageUrl);
			}
			if (StringUtils.isNotBlank(vo.getBarCode())) {
				sp.setBarCode(vo.getBarCode());
			}
			if (vo.getHasTax() >= 0) {
				sp.setHastax(vo.getHasTax());
			}

			if (goods != null && goods.getId() > 0) {
				sp.setGoodsId(String.valueOf(goods.getId()));
			}

			if (StringUtils.isNotBlank(vo.getSpecDesc())) {
				sp.setSpecificationsString(vo.getSpecDesc());
			}
			sp.setPushStatus(Push.WAIT_PUSH.getName());
			if (supplierProductService == null)
				supplierProductService = new SupplierProductServiceImpl();
			supplierProductService.add(sp, false);

			int freight = inventory.getDefaultFreight();
			// 保存SKU价格信息，涉及到有计算
			int private_cost_price = 0;
			if (vo.getHasTax() == 0) {// 不含税
				private_cost_price = inventory.getCooperatePrice() + freight;
			} else {
				private_cost_price = inventory.getTaxCooperatePrice() + freight;
			}
			// 求差价
			int diffPrice = inventory.getSalePrice() - private_cost_price;
			if (diffPrice < 0) {
				log.error("严重警告 ,出现负数................................... 产品SKU ID : " + vo.getId());
			}
			int step = diffPrice / 4; // 四个等级，每级的差价
			SupplierProductPrice _supplierProductPrice = new SupplierProductPrice();
			_supplierProductPrice.setSupplierProductId(sp.getId());
			_supplierProductPrice.setDefaultFreight(freight);
			_supplierProductPrice.setCooperateprice(inventory.getCooperatePrice());
			_supplierProductPrice.setTaxcooperateprice(inventory.getTaxCooperatePrice());
			_supplierProductPrice.setSaleprice(inventory.getSalePrice());
			_supplierProductPrice.setMoneyPrice(inventory.getSalePrice());
			_supplierProductPrice.setLeve1Price(private_cost_price + step + step + step);
			_supplierProductPrice.setLeve2Price(private_cost_price + step + step);
			_supplierProductPrice.setLeve3Price(private_cost_price + step);
			_supplierProductPrice.setLeve4Price(private_cost_price);
			_supplierProductPrice.setCostPrice(private_cost_price);
			_supplierProductPrice.setUnionCostPrice(private_cost_price);
			supplierProductPriceService.add(_supplierProductPrice, false);
		}

	}

	/***
	 * 下载远程图片,存本地，并进行压缩，最后上传阿里云获取外网访问地址 @Title: imageZipUpload @Description:
	 * TODO @param @param remoteUrl @return void @throws
	 */
	public String imageZipUpload(String remoteUrl) {
		String localPath = "/usr/local/jg/";
		String datestr = DateTimeUtil.getDate(new Date(), "yyyyMMdd");
		try {
			String path = localPath + datestr;

			File dir = new File(path);

			if (!dir.exists()) {
				dir.mkdirs();
			}

			String name = UUID.randomUUID().toString().replaceAll("-", "");
			String extName = UrlUtil.getFileExtension(remoteUrl);
			String notZipFilePath = path + "/" + name + "." + extName;
			String zipFilePath = path + "/" + "zip" + name + "." + extName;
			ImageUtil.downloadPicture(remoteUrl, notZipFilePath);
			String localhostPath = ImageUtil.outputQuality(notZipFilePath, 0.5, zipFilePath, new BigDecimal("100"));
			// 上传
			AliyunOssUtil util = new AliyunOssUtil();
			String imageURL = util.uploadImg2Oss(new File(localhostPath));
			return imageURL;
		} catch (Exception e) {
			log.error("压缩上传图片出现错误, 图片源地址: {} , 错误原因: {},{}", remoteUrl, e.getMessage(), e);
		}

		return null;
	}

}
